<?php

$postdata = trim($_POST['imgdata']); //获取图片数数据

list($type,$imgdata) = explode(',',$postdata); //截取图片数据，类型信息和图片数据

if(strstr($type,'image/jpeg') !== ""){
	$ext = '.jpg';
}elseif(strstr($type,'image/gif') !== ""){
	$ext = '.gif';
}elseif(strstr($type,'image/png') !== ""){
	$ext = '.png';
}else{
	$ext = '.jpg';
}


$imgData = base64_decode(str_replace(" ","+",str_replace("data:image/jpeg;base64,","",trim($_POST['imgdata']))));

$photo = time().$ext; // 图片名称

file_put_contents($photo, $imgData,true);



	
	 function upimg(){
		
		$postdata = trim(input('imgdata')); //获取图片数数据
		$path  = 	ROOT_PATH . 'public/static/admin/uploads/cateimg/';
		
		$imgUrl = base64_image_content($postdata,$path);
		
		if($imgUrl){
			return json(['imgeurl'=>$imgUrl,"code"=>1,"msg"=>"上传成功"]);
		}else{
			return json(["code"=>0,"msg"=>"上传失败"]);
		}
		
    }
	
	
	/**
	 * [将Base64图片转换为本地图片并保存]
	 * @param  [Base64] $base64_image_content [要保存的Base64]
	 * @param  [目录] $path [要保存的路径]
	 */
    function base64_image_content($base64_image_content,$path){
		//匹配出图片的格式
		$imgUrl = "/".date('Ymd',time())."/";
		if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
			$type = $result[2];
			$new_file = $path.$imgUrl;
			if(!file_exists($new_file)){
				//检查是否有该文件夹，如果没有就创建，并给予最高权限
				mkdir($new_file, 0700);
			}
			$imgUrl = $imgUrl.time().".{$type}";
			$new_file =  $path.$imgUrl;
			if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
				return $imgUrl;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}


?>